package com.ai.bitcoin.jpa.service;

import com.ai.bitcoin.exception.BusinessException;
import com.ai.bitcoin.jpa.dao.BccSubCoinDao;
import com.ai.bitcoin.jpa.entity.BccSubCoin;
import lombok.Getter;
import org.apache.commons.lang.time.DateUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class BccSubCoinService {
    @Getter
    private final BccSubCoinDao bccSubCoinDao;

    @Autowired
    public BccSubCoinService(BccSubCoinDao bccSubCoinDao) {
        this.bccSubCoinDao = bccSubCoinDao;
    }


    /**
     * 增加bcc服务订阅
     *
     * @param openId 订阅人
     * @param bccId  订阅BCC
     * @param month  订阅时长 单位月
     * @return 1订阅 2续订
     */
    public int subscribeBccService(String openId, String bccId, int month) throws BusinessException {
        if (StringUtils.isEmpty(openId)) {
            throw new BusinessException("400", "openId不能为空");
        }
        if (StringUtils.isEmpty(bccId)) {
            throw new BusinessException("400", "bccId不能为空");
        }
        if (month < 1) {
            throw new BusinessException("400", "month不能小于1");
        }

        int result = 1;
        //可订阅场合
        BccSubCoin subCoin = bccSubCoinDao.queryByBccIdAndUserOpenId(bccId, openId);
        Date endTime;
        if (subCoin == null) {
            subCoin = new BccSubCoin();
            subCoin.setBccId(bccId);
            subCoin.setUserOpenId(openId);
            //未订阅
            endTime = DateUtils.addMonths(new Date(), month);
        }
        else if (subCoin.getStatus() == 0) {
            //已过期的订阅
            endTime = DateUtils.addMonths(new Date(), month);
        }
        else {
            //已订阅 续订
            endTime = DateUtils.addMonths(new Date(subCoin.getEndTime()), month);
            result = 2;
        }
        subCoin.setStatus(1);
        subCoin.setEndTime(endTime.getTime());
        bccSubCoinDao.save(subCoin);
        return result;
    }
}
